import { Service } from "egg";
import { LoginParam } from "../../model/login";
import { loginToken,continueToken } from "../../lib/utljwt";
const md5 = require('md5')






export default class Login extends Service {
    public async login(param: LoginParam) {
        console.log("*******", param)

        if (param && param.username != "") {
            let { ctx } = this;
            console.log("&&&&&&&", ctx.model);
            let user = await ctx.model.User.findByPk(param.username);
            if (user) {
                console.log("&&&&&&&&&&&",user.passsword,param.password)
                if (user.password === param.password) {
                    return { result: {token:loginToken(user.username)} }
                }
            } else {
                if (param.username == 'admin') {
                    console.log("*********not found *********")
                    /*let user = new ctx.model.User();
                    user.username = 'admin';
                    user.group_name = 'admin';
                    user.role_name = 'admin';
                    user.password = '123456';*/
                    const userNew = await ctx.model.User.create({
                        username: 'admin',
                        group_name: 'admin',
                        roles: {roleName:'admin',value:'admin'},
                        password: md5('admin_iotbase@zw'),
                        desc:'超级管理员',
                        
                    });
                    
                    if (userNew.passsword === param.password) {
                        return { result: {token:loginToken(user.username)} }
                    }
                }

            }
        }
        return { error: { code: -1, message: '用户名或密码错误，请检查后重新登录' } }
    }
    public refreshToken(username: string):string{
        return continueToken(username)
    }

    public async getUserInfo(){
        console.log("-------------getuserinfo------",this.ctx.usernameByToken)
        return await this.ctx.model.User.findByPk(this.ctx.usernameByToken)
    }
    
} 